import ollama, { Ollama } from 'ollama/browser'
import { tldLocales } from './locales';


chrome.runtime.onInstalled.addListener(() => {
    console.log("[my first extension] is installed.")
    // 上下文菜单
    for (let [tld, locale] of Object.entries(tldLocales)) {
        chrome.contextMenus.create({
          id: tld,
          title: locale,
          type: 'normal',
          contexts: ['selection'],
        });
    }
})

chrome.bookmarks.onCreated.addListener((id, bookmarks) => {
    // console.log(id)
    // console.log(bookmarks)
    console.log("Created Bookmark")
})


chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log(message)
    // console.log(sender)
    sendResponse({payload: "Hello from the background"})
})


chrome.bookmarks.onMoved.addListener(() => {
    chrome.tabs.query({active: true, currentWindow: true}, tabs => {
        // console.log("Tabs: ", tabs)
        chrome.tabs.sendMessage(
            tabs[0].id, 
            {name: "The Bookmark is moved."},
            (response) => {
                console.log("Response: ", response)
            }
        )
    })
})

let active = false;
function changeTheme(color: string): void {
    console.log("Change BackgroundColor: ", color)
    document.body.style.backgroundColor = color;
   
}

chrome.action.onClicked.addListener(async (tab) => {
    active = !active;
    const color = active ? 'black' : 'white';
    chrome.scripting.executeScript({
        target: {tabId: tab.id ? tab.id : -1},
        func: changeTheme,
        args: [color]
    }).then((value) => {}).catch((error) => {console.error(error)});

    console.log("Start Chat:")
    const response = await ollama.chat({
        model: 'glm4:9b',
        messages: [{ role: 'user', content: '你好，请介绍一下你自己。' }],
    })
    console.log(response.message.content)
});

function logURL(requestDetails: chrome.webRequest.WebRequestBodyDetails) {
    console.log(`Loading: ${requestDetails.url}`)
}

chrome.webRequest.onBeforeRequest.addListener(
    logURL,
    {urls: ["<all_urls>"]}
)


chrome.omnibox.onInputEntered.addListener(async (content) => {
    // Encode user input for special characters , / ? : @ & = + $ #
    // const newURL = `https://www.google.com/search?q=${encodeURIComponent(text)}`;
    // chrome.tabs.create({ url: newURL });
    console.log("User: ", content)
    const response = await ollama.chat({
        model: 'glm4:9b',
        messages: [{ role: 'user', content: content }],
    })
    console.log("AI: ", response.message.content)
  });


chrome.contextMenus.onClicked.addListener((info: chrome.contextMenus.OnClickData, tab) => {
    console.log("ContextMenus: ", info.menuItemId, info.selectionText)
    console.log("ContextMenus: ", tab)
})

chrome.commands.onCommand.addListener((command) => {
    console.log("Command: ", command);
})
  
